package com.zhanghe.mall.service.impl;

import com.zhanghe.mall.pojo.*;
import com.zhanghe.mall.pojo.repository.*;
import com.zhanghe.mall.service.AccountService;
import com.zhanghe.mall.service.vo.AccountPermissionsVO;
import com.zhanghe.mall.service.vo.ManagerPermissionsVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * AccountServiceImpl
 *
 * @author Clevo
 * @date 2018/10/17
 */
@Service
@Transactional(rollbackFor = Throwable.class)
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountRespository accountRespository;
    @Autowired
    private RoleRepository roleRepository;
    @Autowired
    private PermissionsRepository permissionsRepository;
    @Autowired
    private RolePermissionsRepository rolePermissionsRepository;
    @Autowired
    private AccountRoleRepository accountRoleRepository;

    @Override
    public List<AccountPermissionsVO> findAllPermissions(Long accountId,Long systemId) {
        List<AccountPermissionsVO> result = new ArrayList<>();
        List<AccountRole> roles = accountRoleRepository.findByAccount_IdAndRole_System_Id(accountId,systemId);
        List<Long> roleIds = new ArrayList<>();
        for(AccountRole accountRole:roles){
            roleIds.add(accountRole.getRole().getId());
        }
        List<RolePermissions> rolePermissionss = rolePermissionsRepository.findByRole_IdInAndPermissions_TypeOrderByPermissionsSortAsc(roleIds,"menu");
        for(RolePermissions rolePermissions:rolePermissionss){
            if(rolePermissions.getPermissions().getParentId()==null){
                AccountPermissionsVO vo = AccountPermissionsVO.transformFromRolePermissions(rolePermissions);
                getPermissionsChild(vo ,rolePermissionss);
                result.add(vo);
            }
        }
        return result;
    }

    public void getPermissionsChild(AccountPermissionsVO accountPermissionsVO,List<RolePermissions> rolePermissionss){
        List<AccountPermissionsVO> child = new ArrayList<>();
        for(RolePermissions rolePermissions:rolePermissionss){
            if(accountPermissionsVO.getId().equals(rolePermissions.getPermissions().getParentId())){
                AccountPermissionsVO childvo = AccountPermissionsVO.transformFromRolePermissions(rolePermissions);
                getPermissionsChild(childvo ,rolePermissionss);
                child.add(childvo);
            }
        }
        accountPermissionsVO.setChild(child);
    }

    @Override
    public Account findByUserName(String userName) {
        return accountRespository.findByUsername(userName);
    }
}
